package com.jack.leetcode.每日一题;

import java.util.*;
import java.util.stream.Collectors;

/***
 * @author zhangjie
 * @date 2020/4/13 22:05
 */
public class Twitter {
    class tweet{
        int tweetId;
        int weight;
        tweet(int tweetId,int weight){
            this.tweetId = tweetId;
            this.weight = weight;
        }
        public int getWeight(){
            return this.weight;
        }
        public int getTweetId(){
            return this.tweetId;
        }
    }
    int weight;
    Map<Integer,List<tweet>> tweetIdMap;
    Map<Integer,Set<Integer>> followUserIdMap;

    /** Initialize your data structure here. */
    public Twitter() {
        weight = 0;
        tweetIdMap = new HashMap<>();
        followUserIdMap = new HashMap<>();
    }

    /** Compose a new tweet. */
    public void postTweet(int userId, int tweetId) {
        List<tweet> tweetIdList = tweetIdMap.containsKey(userId)?tweetIdMap.get(userId):new ArrayList<>();
        tweetIdList.add(new tweet(tweetId,weight++));
        tweetIdMap.put(userId,tweetIdList);
    }

    /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */
    public List<Integer> getNewsFeed(int userId) {
        List<tweet> tweetIdList = tweetIdMap.containsKey(userId)?tweetIdMap.get(userId):new ArrayList<>();
        List<tweet> result = new ArrayList<>(tweetIdList);
        Set<Integer> followUser = followUserIdMap.containsKey(userId)?followUserIdMap.get(userId):new HashSet<>();
        followUser.forEach(u->{
            List<tweet> followTweetIdList = tweetIdMap.containsKey(u)?tweetIdMap.get(u):new ArrayList<>();
            result.addAll(followTweetIdList);
        });
        return result.stream().sorted(Comparator.comparing(tweet::getWeight).reversed()).map(tweet::getTweetId).distinct().limit(10).collect(Collectors.toList());
    }

    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */
    public void follow(int followerId, int followeeId) {
        Set<Integer> followUser = followUserIdMap.containsKey(followerId)?followUserIdMap.get(followerId):new HashSet<>();
        followUser.add(followeeId);
        followUserIdMap.put(followerId,followUser);
    }

    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */
    public void unfollow(int followerId, int followeeId) {
        Set<Integer> followUser = followUserIdMap.containsKey(followerId)?followUserIdMap.get(followerId):new HashSet<>();
        followUser.remove(followeeId);
        followUserIdMap.put(followerId,followUser);
    }
}
